package cn.zkcloud.handler;

import cn.zkcloud.servlet.HttpContext;
import cn.zkcloud.util.Proty;
import org.apache.log4j.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Iterator;

/**
 * @Author zk
 * @Date 2017/6/18.
 * @Email zkdcloud_cn@163.com
 */
public class StaticResourcesHandler implements Handler{
    Logger logger = Logger.getLogger(StaticResourcesHandler.class);

    /**
     * defalut servlet operator static resources
     */
    private static final String DEFAULT_SERVELT = "default";

    /** default servlet by jetty ,tomcat,jboss...
     *
     */
    private RequestDispatcher requestDispatcher;


    public StaticResourcesHandler(ServletContext servletContext){
        this.requestDispatcher = servletContext.getNamedDispatcher(DEFAULT_SERVELT);
        logger.info("StaticResourcesHandler init...");
    }


    public void handler(HttpContext httpContext, Iterator<Handler> iterator) {
        try {
            if(isStaticPath(httpContext.getRequest())){
                requestDispatcher.forward(httpContext.getRequest(),httpContext.getResponse());
                logger.debug("this request is static request");
                return;
            }
        } catch (ServletException e) {
            logger.error("judge requestDispatcher error");
        } catch (IOException e) {
            logger.error("get requestDispatcher error");
        }

        if(iterator.hasNext()){
            iterator.next().handler(httpContext,iterator);
        }
    }

    /** isStaticRequest
     *
     * @param request
     * @return
     */
    public boolean isStaticPath(HttpServletRequest request){
        String path = request.getRequestURI();
        return Proty.StaticResources.isStaticPath(path);
    }
}
